import { Effect, Reducer } from 'umi';

import { CurrentInfo, query as queryUser } from '@/services/user';
import { accountLogin } from '@/services/login';

export interface CurrentUser {
  avatar?: string;
  name?: string;
  title?: string;
  userid?: string;
}

export interface UserModelState {
  currentUser?: CurrentUser;
  token?: string;
}

export interface UserModelType {
  namespace: string;
  state: UserModelState;
  effects: {
    fetch: Effect;
    fetchCurrent: Effect;
    login: Effect;
    logout: Effect;
  };
  reducers: {
    saveCurrentUser: Reducer<UserModelState>;
    changeNotifyCount: Reducer<UserModelState>;
    changeLoginStatus: Reducer<UserModelState>;
  };
}

const UserModel: UserModelType = {
  namespace: 'user',
  state: {
    currentUser: {},
  },
  effects: {
    *fetch(_, { call, put }) {
      const response = yield call(queryUser);
      yield put({
        type: 'saveCurrentUser',
        payload: response,
      });
    },
    *fetchCurrent(_, { call, put }) {
      const response = yield call(CurrentInfo);
      yield put({
        type: 'saveCurrentUser',
        payload: response,
      });
    },
    *login({ payload }, { call, put }) {
      const response = yield call(accountLogin, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
    },
    *logout({ payload }) {},
  },
  reducers: {
    saveCurrentUser(state, action) {
      return {
        ...state,
        currentUser: action.payload || {},
      };
    },
    changeNotifyCount(state = { currentUser: {} }, action) {
      return {
        ...state,
        currentUser: {
          ...state.currentUser,
          notifyCount: action.payload.totalCount,
        },
      };
    },
    changeLoginStatus(state, { payload }) {
      return {
        ...state,
        status: payload.status,
        token: payload.token,
      };
    },
  },
};

export default UserModel;
